package com.beka.frame.base;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import com.ibatis.sqlmap.engine.builder.xml.SqlMapClasspathEntityResolver;
import com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient;
import com.ibatis.sqlmap.engine.transaction.TransactionConfig;
import com.ibatis.sqlmap.engine.transaction.TransactionManager;
import com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig;
import com.metarnet.util.XMLUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy;
import org.w3c.dom.Document;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.Properties;

/**
 * Created by IntelliJ IDEA.
 * User: Administrator
 * Date: 12-4-17
 * Time: 下午11:50
 * 改写替换org.springframework.orm.ibatis.SqlMapClientFactoryBean类，以实现加载ibatis配置文件时可以使用通配符*号
 */

public class SqlMapClientFactoryBean implements FactoryBean, InitializingBean {

    protected transient final Log logger = LogFactory.getLog(getClass());

    private String configLocation;
    private Properties sqlMapClientProperties;
    private DataSource dataSource;
    private boolean useTransactionAwareDataSource = true;
    private Class transactionConfigClass = ExternalTransactionConfig.class;
    private Properties transactionConfigProperties;
    private SqlMapClient sqlMapClient;

    public SqlMapClientFactoryBean() {
        this.transactionConfigProperties = new Properties();
        this.transactionConfigProperties.setProperty("SetAutoCommitAllowed", "false");
    }

    /**
     * Set the location of the iBATIS SqlMapClient config file.
     * A typical value is "WEB-INF/sql-map-config.xml".
     *
     * @param configLocation 配置文件位置
     */
    public void setConfigLocation(String configLocation) {
        this.configLocation = configLocation;
    }

    /**
     * Set optional properties to be passed into the SqlMapClientBuilder, as
     * alternative to a <code>&lt;properties&gt;</code> tag in the sql-map-config.xml
     * file. Will be used to resolve placeholders in the config file.
     *
     * @param sqlMapClientProperties sqlMapClient属性
     * @see #setConfigLocation
     * @see com.ibatis.sqlmap.client.SqlMapClientBuilder#buildSqlMapClient(java.io.Reader, java.util.Properties)
     */
    public void setSqlMapClientProperties(Properties sqlMapClientProperties) {
        this.sqlMapClientProperties = sqlMapClientProperties;
    }

    /**
     * Set the DataSource to be used by iBATIS SQL Maps. This will be passed to the
     * SqlMapClient as part of a TransactionConfig instance.
     * <p>If specified, this will override corresponding settings in the SqlMapClient
     * properties. Usually, you will specify DataSource and transaction configuration
     * <i>either</i> here <i>or</i> in SqlMapClient properties.
     * <p>Specifying a DataSource for the SqlMapClient rather than for each individual
     * DAO allows for lazy loading, for example when using PaginatedList results.
     * <p>With a DataSource passed in here, you don't need to specify one for each DAO.
     * Passing the SqlMapClient to the DAOs is enough, as it already carries a DataSource.
     * Thus, it's recommended to specify the DataSource at this central location only.
     * <p>Thanks to Brandon Goodin from the iBATIS team for the hint on how to make
     * this work with Spring's integration strategy!
     *
     * @param dataSource 数据源
     * @see #setTransactionConfigClass
     * @see #setTransactionConfigProperties
     * @see com.ibatis.sqlmap.client.SqlMapClient#getDataSource
     * @see org.springframework.orm.ibatis.SqlMapClientTemplate#setDataSource
     * @see org.springframework.orm.ibatis.SqlMapClientTemplate#
     */
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * Set whether to use a transaction-aware DataSource for the SqlMapClient.
     * <p>Default is true: If the SqlMapClient performs direct database operations
     * outside of Spring's SqlMapClientTemplate -- for example, lazy loading or
     * direct SqlMapClient access --, it will still participate in active
     * Spring-managed transactions.
     * <p>Turn this flag off to get raw DataSource handling, without Spring
     * transaction checks. Operations on Spring's SqlMapClientTemplate will
     * still detect Spring-managed transactions, but lazy loading or direct
     * SqlMapClient access won't.
     *
     * @param useTransactionAwareDataSource 是否使用事务提醒数据源
     * @see org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
     * @see org.springframework.orm.ibatis.SqlMapClientTemplate
     * @see com.ibatis.sqlmap.client.SqlMapClient
     */
    public void setUseTransactionAwareDataSource(boolean useTransactionAwareDataSource) {
        this.useTransactionAwareDataSource = useTransactionAwareDataSource;
    }

    /**
     * Set the iBATIS TransactionConfig class to use. Default is
     * <code>com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig</code>.
     * <p>Will only get applied when using a Spring-managed DataSource.
     * An instance of this class will get populated with the given DataSource
     * and initialized with the given properties.
     * <p>The default ExternalTransactionConfig is appropriate if there is
     * external transaction management that the SqlMapClient should participate
     * in: be it Spring transaction management, EJB CMT or plain JTA. This
     * should be the typical scenario. If there is no active transaction,
     * SqlMapClient operations will execute SQL statements non-transactionally.
     * <p>JdbcTransactionConfig or JtaTransactionConfig is only necessary
     * when using the iBATIS SqlMapTransactionManager API instead of external
     * transactions. If there is no explicit transaction, SqlMapClient operations
     * will automatically start a transaction for their own scope (in contrast
     * to the external transaction mode, see above).
     * <p><b>It is strongly recommended to use iBATIS SQL Maps with Spring
     * transaction management (or EJB CMT).</b> In this case, the default
     * ExternalTransactionConfig is fine. Lazy loading and SQL Maps operations
     * without explicit transaction demarcation will execute non-transactionally.
     * <p>Even with Spring transaction management, it might be desirable to
     * specify JdbcTransactionConfig: This will still participate in existing
     * Spring-managed transactions, but lazy loading and operations without
     * explicit transaction demaration will execute in their own auto-started
     * transactions. However, this is usually not necessary.
     *
     * @param transactionConfigClass ?
     * @see #setDataSource
     * @see #setTransactionConfigProperties
     * @see com.ibatis.sqlmap.engine.transaction.TransactionConfig
     * @see com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig
     * @see com.ibatis.sqlmap.engine.transaction.jdbc.JdbcTransactionConfig
     * @see com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig
     * @see com.ibatis.sqlmap.client.SqlMapTransactionManager
     */
    public void setTransactionConfigClass(Class transactionConfigClass) {
        if (transactionConfigClass == null || !TransactionConfig.class.isAssignableFrom(transactionConfigClass)) {
            throw new IllegalArgumentException("Invalid transactionConfigClass: does not implement " +
                    "com.ibatis.sqlmap.engine.transaction.TransactionConfig");
        }
        this.transactionConfigClass = transactionConfigClass;
    }

    /**
     * Set properties to be passed to the TransactionConfig instance used
     * by this SqlMapClient. Supported properties depend on the concrete
     * TransactionConfig implementation used:
     * <p><ul>
     * <li><b>ExternalTransactionConfig</b> supports "DefaultAutoCommit"
     * (default: false) and "SetAutoCommitAllowed" (default: true).
     * Note that Spring uses SetAutoCommitAllowed = false as default,
     * in contrast to the iBATIS default, to always keep the original
     * autoCommit value as provided by the connection pool.
     * <li><b>JdbcTransactionConfig</b> does not supported any properties.
     * <li><b>JtaTransactionConfig</b> supports "UserTransaction"
     * (no default), specifying the JNDI location of the JTA UserTransaction
     * (usually "java:comp/UserTransaction").
     * </ul>
     *
     * @param transactionConfigProperties ?
     * @see com.ibatis.sqlmap.engine.transaction.TransactionConfig#initialize
     * @see com.ibatis.sqlmap.engine.transaction.external.ExternalTransactionConfig
     * @see com.ibatis.sqlmap.engine.transaction.jdbc.JdbcTransactionConfig
     * @see com.ibatis.sqlmap.engine.transaction.jta.JtaTransactionConfig
     */
    public void setTransactionConfigProperties(Properties transactionConfigProperties) {
        this.transactionConfigProperties = transactionConfigProperties;
    }


    public void afterPropertiesSet() throws Exception {
        if (this.configLocation == null) {
            throw new IllegalArgumentException("configLocation is required");
        }

        try {
            this.sqlMapClient = (this.sqlMapClientProperties != null) ?
                    SqlMapClientBuilder.buildSqlMapClient(getSqlMapReader(this.configLocation), this.sqlMapClientProperties) :
                    SqlMapClientBuilder.buildSqlMapClient(getSqlMapReader(this.configLocation));

            // Tell the SqlMapClient to use the given DataSource, if any.
            if (this.dataSource != null) {
                TransactionConfig transactionConfig = (TransactionConfig) this.transactionConfigClass.newInstance();
                DataSource dataSourceToUse = this.dataSource;
                if (this.useTransactionAwareDataSource) {
                    dataSourceToUse = new TransactionAwareDataSourceProxy(this.dataSource);
                }
                transactionConfig.setDataSource(dataSourceToUse);
                transactionConfig.initialize(this.transactionConfigProperties);
                applyTransactionConfig(this.sqlMapClient, transactionConfig);
            }
        } catch (Exception e) {
            logger.error(e);
        }
    }

    private Reader getSqlMapReader(String config) {
        if (config == null) {
            throw new IllegalArgumentException("configLocation is required");
        }
        Document doc;
        Reader reader = null;
        try {
            /* 获取匹配的sqlmap文件资源 */
            Resource[] resources = ServletResourcePatternResovlerAndLoader.getResourceArray(config);
            if (resources == null || resources.length == 0) {
                throw new IllegalArgumentException("configLocation is required");
            }
            doc = XMLUtils.getDocument(resources[0].getInputStream(), new SqlMapClasspathEntityResolver());
            logger.info("ok" + resources[0].getFilename());
            if (resources.length > 1) {
                for (int i = 1; i < resources.length; i++) {
                    doc = XMLUtils.mergeDocument(doc, XMLUtils.getDocument(resources[i].getInputStream(), new SqlMapClasspathEntityResolver()));
                    logger.info("files" + resources[i].getFilename());
                }
            }
            reader = getReaderFromDocument(doc);
        } catch (IOException e) {
            logger.error("files", e);
        } catch (Exception e) {
            logger.error("files", e);
        }
        return reader;
    }

    /**
     * 获取文档对象的读取器
     *
     * @param doc xml文档对象，字符输入流的数据源
     * @return 字符输入流
     */

    private Reader getReaderFromDocument(Document doc) {
        return new StringReader(XMLUtils.getXmlString(doc));
    }

    /**
     * Apply the given iBATIS TransactionConfig to the SqlMapClient.
     * <p>Default implementation casts to ExtendedSqlMapClient, retrieves the maximum
     * number of concurrent transactions from the SqlMapExecutorDelegate, and sets
     * an iBATIS TransactionManager with the given TransactionConfig.
     *
     * @param sqlMapClient      the SqlMapClient to apply the TransactionConfig to
     * @param transactionConfig the iBATIS TransactionConfig to apply
     * @see com.ibatis.sqlmap.engine.impl.ExtendedSqlMapClient
     * @see com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate#getMaxTransactions
     * @see com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate#setTxManager
     */
    protected void applyTransactionConfig(SqlMapClient sqlMapClient, TransactionConfig transactionConfig) {
        if (!(this.sqlMapClient instanceof ExtendedSqlMapClient)) {
            throw new IllegalArgumentException(
                    "Cannot set TransactionConfig with DataSource for SqlMapClient if not of type " +
                            "ExtendedSqlMapClient: " + this.sqlMapClient);
        }
        ExtendedSqlMapClient extendedClient = (ExtendedSqlMapClient) this.sqlMapClient;
        transactionConfig.setMaximumConcurrentTransactions(extendedClient.getDelegate().getMaxTransactions());
        extendedClient.getDelegate().setTxManager(new TransactionManager(transactionConfig));
    }


    public Object getObject() {
        return this.sqlMapClient;
    }

    public Class getObjectType() {
        return (this.sqlMapClient != null ? this.sqlMapClient.getClass() : SqlMapClient.class);
    }

    public boolean isSingleton() {
        return true;
    }
}

